package com.gitee.wsl.func.transform.sample

import com.gitee.wsl.func.transform.Transformer

/**
 * Transformer implementation that returns the value held in a specified map
 * using the input parameter as a key.
 *
 * @param <T> the type of the input to the function.
 * @param <R> the type of the result of the function.
 * @since 3.0
</R></T> */
class MapTransformer<T, R>(
    /** The map of data to lookup in  */
    val map: Map< T,  R>,
) : Transformer<T, R> {
    /**
     * Gets the map to lookup in.
     *
     * @return the map
     * @since 3.1
     */

    /**
     * Transforms the input to result by looking it up in a `Map`.
     *
     * @param input  the input object to transform
     * @return the transformed result
     */
    override fun transform(input: T): R {
        return map[input] as R
    }

    companion object {

        /**
         * Creates the transformer.
         *
         *
         * If the map is null, a transformer that always returns null is returned.
         *
         * @param <I>  the input type
         * @param <O>  the output type
         * @param map the map, not cloned
         * @return the transformer
        </O></I> */
        fun <I, O> mapTransformer(map: Map< I,O>?): Transformer<I, O> {
            if (map == null) {
                return ConstantTransformer.nullTransformer()
            }
            return MapTransformer(map)
        }
    }
}
